//
//  CCSaoma.swift
//  saoma
//
//  Created by ccl on 16/4/1.
//  Copyright © 2016年 CC. All rights reserved.
//  封装扫描, 扫描界面动画

import UIKit
import AVFoundation
class CCSaoma: UIView, AVCaptureMetadataOutputObjectsDelegate {
    /// 实例化类方法.
    class func CreatCCSaoma()-> CCSaoma{
        return CCSaoma().initSaomaView();
    }
    
    func initSaomaView() -> CCSaoma{
        // 这个白色必须设置
        self.backgroundColor = UIColor.whiteColor();
        return self;
    }
    
    func creatDefult(){
        creatSession();
        setupLayers();
        
        // 创建动画
        creatQRCodeAnimate();
    }
    /// 创建冲击波效果
    func creatQRCodeAnimate() {
        creatContainerView();
        creatBackgroundImage();
        creatQRAnimationImage();
    }
    /// 容器视图
  private  let containerView: UIView = UIView();
    /// 创建容器视图
  private  func creatContainerView(){
        containerView.backgroundColor = UIColor.clearColor();
    // 减除超出边界的
       containerView.clipsToBounds = true;
       
        self.addSubview(containerView);
        // 取消系统布局, 自己添加约束
        containerView.translatesAutoresizingMaskIntoConstraints = false;
        // 中心对齐
        addConstraint(NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0));
        addConstraint(NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0));
        // 左右 20
     addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[sub]-20-|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: ["sub" : containerView]));
        
     // 宽高相等
        addConstraint(NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: containerView, attribute: NSLayoutAttribute.Height, multiplier: 1.0, constant: 0.0));
    }
    /// 扫描动画部分的背景image
   private var  QRBackImage: UIImageView?;
     /// 创建扫描动画部分的背景image
   private func creatBackgroundImage() {
        let image = UIImage(named: "qrcode_border");
        QRBackImage = UIImageView(image: image);
        containerView.addSubview(QRBackImage!);
        
        QRBackImage?.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[sub]|", options: NSLayoutFormatOptions.AlignAllLastBaseline, metrics: nil, views: ["sub" : QRBackImage!]));
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[sub]|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: ["sub" : QRBackImage!]));
    }
    
    /// 二维码冲击波图片top约束
   private var QRAnimationImage: UIImageView?;
    /// 创建二维码冲击波图片
  private  var QRAnimationImageTopContraint: NSLayoutConstraint?;
  private  func creatQRAnimationImage(){
    
        let image = UIImage(named: "qrcode_scanline_qrcode");
        QRAnimationImage = UIImageView(image: image);
        
        containerView.addSubview(QRAnimationImage!);
        
        QRAnimationImage?.translatesAutoresizingMaskIntoConstraints = false;
        // 顶部对齐
        QRAnimationImageTopContraint = NSLayoutConstraint(item: QRAnimationImage!, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem:containerView , attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: -self.containerView.frame.height)
        addConstraint(QRAnimationImageTopContraint!);
        // 等宽
        addConstraint(NSLayoutConstraint(item: QRAnimationImage!, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: containerView, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 1.0));
        // 等高
        addConstraint(NSLayoutConstraint(item: QRAnimationImage!, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: containerView, attribute: NSLayoutAttribute.Height, multiplier: 1.0, constant: 1.0));
        // 等中心 X
        addConstraint(NSLayoutConstraint(item: QRAnimationImage!, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: containerView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 1.0));
    }
    /// 开启冲击波动画
    func creatStartQRAnimation(){
        
        self.QRAnimationImageTopContraint?.constant = -self.containerView.frame.height;
        self.layoutIfNeeded();
        
        UIView.animateWithDuration(2.0) {
            self.QRAnimationImageTopContraint?.constant = self.containerView.frame.height;
            // 循环次数
            UIView.setAnimationRepeatCount(MAXFLOAT);
            // 注意这个顺序不能写反了  否则没有循环.
             self.layoutIfNeeded();
        }
    
    }
    /// 关闭冲击波动画
    func creatCloseQRAnimation(){
       // 移除所有动画效果
        self.layer.removeAllAnimations();
    }
    
    /// 开始扫描
    func startSaoma(){
        
        print("开始扫描")
        session.startRunning();
    }
    /// 结束扫描
    
    
    // 设置回话
   private func creatSession(){
        if !session.canAddInput(inputDevice){
            return;
        }
        if !session.canAddOutput(outPutDate){
            return;
        }
        // 检测完毕. 给回话添加输入,输出设备
        session.addInput(inputDevice);
        session.addOutput(outPutDate);
        
        // 设置 元数据 检测数据的类型
        outPutDate.metadataObjectTypes = outPutDate.availableMetadataObjectTypes;
        // 设置代理
        outPutDate.setMetadataObjectsDelegate(self, queue:dispatch_get_main_queue());
    }
    // MARK: 输出代理
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        print(metadataObjects);
    }
    
    // 设置预览图层
   private func setupLayers(){
        //设置绘画线图层
        drawLayer.frame = self.bounds;
    
        self.layer.insertSublayer(drawLayer, atIndex: 0);
        // 设置图层大小
        previewLayer.frame = self.bounds;
        // 设置图层填充模式 据说不设置, 4s 会有影响  设置的是填充模式
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        //现将drawLayer 放置最下层, 在将previewLayer 放置最下层.  现在previewLayer在最下层
        self.layer.insertSublayer(previewLayer, atIndex: 0);
    }
    
    
    // MARK: 懒加载
    // 绘制线的图层
    lazy var drawLayer:CALayer = {
        return CALayer();
    }()
    
    //预览图层
    lazy var previewLayer:AVCaptureVideoPreviewLayer = {
        
        return AVCaptureVideoPreviewLayer(session: self.session);
    }()
    
    // 回话
    lazy var session:AVCaptureSession = {
        return  AVCaptureSession()
    }()
    // 输入设备
    lazy var inputDevice:AVCaptureDeviceInput? = {
        
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo);
        do{
            return  try AVCaptureDeviceInput(device: device)
        }catch{
            return nil;
        }
        
    }()
    // 输出设备
    lazy var outPutDate: AVCaptureMetadataOutput = {
        
        return AVCaptureMetadataOutput();
    }()

    
}
